package com.zhentao.service.impl;

import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.zhentao.api.user.UserApi;
import com.zhentao.api.userCoupon.UserCouponApi;
import com.zhentao.mapper.CdzZnxMapper;
import com.zhentao.mapper.ChargePayCouponMapper;
import com.zhentao.mapper.ChargePayOrderMapper;
import com.zhentao.model.common.dtos.PageResponseResult;
import com.zhentao.model.common.dtos.ResponseResult;
import com.zhentao.model.common.pojo.pay.CdzZnx;
import com.zhentao.model.common.pojo.pay.ChargePayCoupon;
import com.zhentao.model.common.pojo.pay.ChargePayOrder;
import com.zhentao.model.common.pojo.pay.dtos.OrderQueryDTO;
import com.zhentao.model.common.pojo.pay.dtos.PayDto;
import com.zhentao.model.common.pojo.pay.vo.PayOrderVo;
import com.zhentao.model.common.pojo.users.Users;
import com.zhentao.model.common.pojo.users.param.UserBalanceParam;
import com.zhentao.service.IChargePayOrderService;
import com.zhentao.userLocal.UserThreadLocalUtil;
import com.zhentao.util.SmsService;
import com.zhentao.util.SnowflakeIdGenerator;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.time.LocalDateTime;
import java.util.Date;
import java.util.List;
import java.util.stream.Collectors;

@Service
@Transactional
public class ChargePayOrderServiceImpl extends ServiceImpl<ChargePayOrderMapper, ChargePayOrder> implements IChargePayOrderService {
    @Resource
    private ChargePayCouponMapper chargePayCouponMapper;
    @Autowired
    private UserApi userApi;
    @Autowired
    private UserCouponApi userCouponApi;
    @Autowired
    private CdzZnxMapper cdznxMapper;
    @Autowired
    private CdzZnxMapper cdzZnxMapper;
    public ResponseResult perpayTest(PayDto payDto) {
        ChargePayOrder chargePayOrder = new ChargePayOrder();
        if (payDto.getChargeRecordId() == null) {
            //充值
            chargePayOrder.setOrderType(1);
        }else {
            //充电支付
            chargePayOrder.setOrderType(0);
            chargePayOrder.setChargeRecordId(payDto.getChargeRecordId());
        }
        chargePayOrder = getChargePayOrder(payDto, chargePayOrder);

        // 判断是否是余额支付
        boolean b = payDto.getChannelId().equals("9");
        if (b) {
            String BalancePay = "BalancePay";
            try {
                chargePayOrder.setPayStatus(1);
                // TODO 扣减用户的余额和优惠卷数量
                deductionsUserBalanceAndCouponMount(payDto);
                deleteUserConpon(chargePayOrder);
                // 支付成功


                chargePayOrder.setPayStatus(2);
                // 设置付款时间
                chargePayOrder.setCreateTime(new Date());
                this.updateById(chargePayOrder);
                return ResponseResult.okResult(BalancePay);
            } catch (Exception e) {
                chargePayOrder.setPayStatus(0);
                chargePayOrder.setCreateTime(new Date());
                this.updateById(chargePayOrder);
                return ResponseResult.errorResult(501, "支付失败");
            }
        }

        return ResponseResult.okResult(chargePayOrder.getOrderNo());
    }

    private void deleteUserConpon(ChargePayOrder chargePayOrder) {
        // TODO 删除用户的优惠卷
        List<ChargePayCoupon> chargePayCouponList = chargePayCouponMapper
                .selectList(Wrappers.<ChargePayCoupon>lambdaQuery().eq(ChargePayCoupon::getPayId, chargePayOrder.getId()));

        List<Integer> couponIds = chargePayCouponList.stream()
                .map(ChargePayCoupon::getCouponId)
                .collect(Collectors.toList());

        userCouponApi.deleteUserCoupon(couponIds, chargePayOrder.getUserId());
    }

    private void deductionsUserBalanceAndCouponMount(PayDto payDto) {
        UserBalanceParam userBalanceParam = new UserBalanceParam();
        userBalanceParam.setChannelId(payDto.getChannelId());
        userBalanceParam.setAmount(payDto.getInitialAmount());
        userBalanceParam.setUserId(UserThreadLocalUtil.getUser());
        userBalanceParam.setOrderType(0);
        userBalanceParam.setCouponMount(payDto.getUserCouponIdList().length);
        userApi.updateBalance(userBalanceParam);
    }

    private ChargePayOrder getChargePayOrder(PayDto payDto, ChargePayOrder chargePayOrder) {
        //获取用户id
        Long userId = UserThreadLocalUtil.getUser();
        //        订单号, 雪花算法生成
        chargePayOrder.setOrderNo(new SnowflakeIdGenerator().nextId());
//        支付金额(优惠后的金额）
        chargePayOrder.setAmount(payDto.getAmount());
//        添加金额，添加进订单的金额
        chargePayOrder.setInitialAmount(payDto.getInitialAmount());
        chargePayOrder.setChannelId(payDto.getChannelId());
        chargePayOrder.setPayStatus(1);
//        付款人
        chargePayOrder.setUserId(UserThreadLocalUtil.getUser());
        this.save(chargePayOrder);

        Integer[] userCouponIdList = payDto.getUserCouponIdList();

        for (Integer couponId : userCouponIdList) {
            ChargePayCoupon chargePayCoupon = new ChargePayCoupon();
            chargePayCoupon.setPayId(chargePayOrder.getId());
            chargePayCoupon.setCouponId(couponId);
            chargePayCouponMapper.insert(chargePayCoupon);
        }
        String phoneNumber = cdzZnxMapper.getPhoneNumberByUserId(userId);

        CdzZnx cdzZnx = new CdzZnx();
        cdzZnx.setUserId(userId);
        cdzZnx.setSendTime(LocalDateTime.now());
        cdzZnx.setTitle("充值/汽车充电");
        cdzZnx.setContent("充值支付成功");
        cdzZnx.setCreateTime(LocalDateTime.now());
        cdzZnx.setIsRead(0);
        cdzZnx.setPhone(phoneNumber);
        cdznxMapper.insert(cdzZnx);


        ChargePayOrder byId = this.getById(chargePayOrder.getId());

        // 生成一个验证码
        String verificationCode = generateVerificationCode();
        // 调用短信发送方法
        SmsService.sendVerificationCode(phoneNumber, verificationCode);
        return byId;
    }
    @Resource
    private ChargePayOrderMapper chargePayOrderMapper;
    @Override
    public ResponseResult OrderQuery(OrderQueryDTO orderQueryDTO) {
        /*
         * 1. 查询支付订单
         * 1.1 查询用户自己的支付订单
         * 1.2 根据状态进行查询
         * 1.3 分页查询
         * 1.5 查询出该订单的支付位置（使用什么进行支付）
         * 1.5 封装成vo类进行返回
         **/
        PageHelper.startPage(orderQueryDTO.getCurrentPage(), orderQueryDTO.getPageSize());
        Long userId = UserThreadLocalUtil.getUser();
        // 设置用户id
        orderQueryDTO.setUserId(userId);
        List<PayOrderVo> payOrderVos = chargePayOrderMapper.selectOrderQuery(orderQueryDTO);
        PageInfo pageInfo = new PageInfo(payOrderVos);

        PageResponseResult pageResponseResult = new PageResponseResult(orderQueryDTO.getCurrentPage(), orderQueryDTO.getPageSize(), (int)pageInfo.getTotal());
        pageResponseResult.setData(pageInfo.getList());

        return pageResponseResult;
    }

    private String generateVerificationCode() {
        // 你可以自定义验证码生成的方式，这里我们直接返回一个简单的验证码
        return String.valueOf((int) (Math.random() * 900000) + 100000);  // 生成一个6位数字验证码
    }
}
